<template>
    <div>
        <div class="content" :style="height">
            <div class="bar-chart white-block">
<!--                <p>服务分析</p>-->
                <breadcrumb :title="'服务分析'">
                    <div class="text-right">
                        <el-select v-model="infoForm.servcode"
                                   placeholder="请选择"
                                   @change="getServname"
                                   ref="select"
                                   @visible-change="visibleChange"
                                   filterable>
                            <el-option v-for="item in infoForm.serviceOptions"
                                       :key="item.serviceid"
                                       :label="item.servname + ' (' + item.servcode + ') '"
                                       :value="item.servcode">
                            </el-option>
                        </el-select>
                        <el-date-picker
                            v-model="newTime"
                            class="ml10"
                            align="right"
                            :picker-options="pickerOptions"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="~"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                        <el-button type="primary" class="ml10" @click="queryChartData">查询</el-button>
                        <span class="ml10" @click="download"><i class="iconfont el-icon-download"></i></span>
                    </div>
                </breadcrumb>

                <div class="img" v-if="data">
                    <img src="../../../static/images/noData.png" alt="">
                    <div>暂无数据</div>
                </div>
                <div id="chart" class="box" v-if="chartFlag"></div>
            </div>
            <div class="mt20  white-block polyline-chart" v-if="flag">
                <div id="polyline" class="polyline-box"></div>
            </div>
        </div>
    </div>
</template>

<script>
    import echarts from 'echarts'
    import qs from 'qs'
    import breadcrumb from '../../components/breadcrumb'

    export default {
        data() {
            return {
                infoForm: {
                    serviceOptions: [],
                    servcode: ''
                },
                serviceid: '',
                newTime: '',
                height: {
                    height: ''
                },
                curve: [],
                number: [],
                details: [],
                barYData: [],
                barDataList: [],
                lineXData: [],
                lineDataList: [],
                flag: false,
                chartFlag: false,
                data: true,
                pickerOptions: {
                    disabledDate: (time) => {
                        const day = 30 * 24 * 3600 * 1000,
                            minTime = new Date() - day,
                            maxTime = new Date()
                        return time.getTime() < minTime || time.getTime() > maxTime
                    }
                }
            }
        },
        mounted() {
            this.getSelect()
            const start = this.$filter.timeFormat(new Date(new Date().toLocaleDateString()), 'YYYY-MM-DD HH:mm:ss'),
                end = this.$filter.timeFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
            this.newTime = [start, end]
        },
        methods: {
            // 初始化echart
            getEchart() {
                let myChart, myPolylineChart, _this = this
                myChart = echarts.init(document.getElementById('chart'))
                myChart.setOption({
                    color: ['#5586FB'],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: '' // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    dataZoom: [
                        {
                            type: 'slider',
                            show: true, // flase直接隐藏图形
                            yAxisIndex: [0],
                            height: '80%',
                            width: 15,
                            zoomOnMouseWheel: true,
                            showDetail: false,
                            right: '0%', // 滚动条靠左侧的百分比
                            bottom: '15%',
                            start: 0, // 滚动条的起始位置
                            end: 70 // 滚动条的截止位置（按比例分割你的柱状图x轴长度）
                        },
                        {
                            type: 'inside',
                            yAxisIndex: [0],
                            start: 0,
                            end: 50
                        }
                    ],
                    grid: {
                        x: 180,
                        y: 25,
                        x2: 80,
                        y2: 35
                    }, // 设置图标旁边留白部分大小
                    xAxis: [
                        {
                            type: 'value',
                            splitLine: {
                                show: true,
                                lineStyle: {
                                    type: 'dashed'
                                }
                            }, // 设置刻度线条变成虚线
                            axisLabel: { // X轴线 标签修改
                                textStyle: {
                                    color: '#8c8c92' // 坐标值得具体的颜色
                                }
                            },
                            axisLine: {
                                show: true, // X轴 网格线 颜色类型的修改
                                lineStyle: {
                                    type: 'solid',
                                    color: '#eee'
                                }
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'category',
                            data: this.barYData,
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: { // y轴线 标签修改
                                interval: 0,
                                margin: 20,
                                formatter: function (params) {
                                    let newParamsName = '',
                                        paramsNameNumber = params.length,
                                        provideNumber = 12,
                                        rowNumber = Math.ceil(paramsNameNumber / provideNumber)
                                    if (paramsNameNumber > provideNumber) {
                                        for (var p = 0; p < rowNumber; p++) {
                                            let tempStr = '',
                                                start = p * provideNumber,
                                                end = start + provideNumber
                                            if (p === rowNumber - 1) {
                                                tempStr = params.substring(start, paramsNameNumber)
                                            } else {
                                                if (p > 2) {
                                                    tempStr = '...'
                                                    newParamsName += tempStr
                                                    break
                                                } else {
                                                    tempStr = params.substring(start, end)
                                                    if (p < 2) {
                                                        tempStr += '\n'
                                                    }
                                                }
                                            }
                                            newParamsName += tempStr
                                        }

                                    } else {
                                        newParamsName = params
                                    }
                                    return newParamsName
                                },
                                rich: {
                                    value: {
                                        width: 100
                                    }
                                },
                                textStyle: {
                                    color: '#8c8c92' // 坐标值得具体的颜色
                                }
                            },
                            axisLine: {
                                show: true, // y轴 网格线 颜色类型的修改
                                lineStyle: {
                                    type: 'solid',
                                    color: '#eee'
                                }
                            }
                        }
                    ],
                    series: [
                        {
                            name: '',
                            type: 'bar',
                            barWidth: '40',
                            data: this.barDataList
                        }
                    ]
                })

                myPolylineChart = echarts.init(document.getElementById('polyline'))
                myPolylineChart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: '' // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function (params) {
                            if (params[0].data === 0) {
                                params = params[0].seriesName + ':' + params[0].data
                                if (params) return params
                            } else {
                                for (let i = 0; i < _this.curve.length; i++) {
                                    if (params[0].axisValue === _this.curve[i].date) {
                                        _this.number = _this.curve[i].detail
                                    }
                                }
                                let params1 = []
                                for (let i = 0; i < _this.number.length; i++) {
                                    params1.push(_this.number[i].name + '：' + _this.number[i].count + '<br/>')
                                }
                                params = params[0].seriesName + '：' + params[0].data + '<br/>' + params1.join('')
                                if (params) return params
                            }
                        }
                    },
                    color: ['#5586FB'],
                    dataZoom: [
                        {
                            type: 'slider',
                            show: true, // flase直接隐藏图形
                            xAxisIndex: [0],
                            height: '5%',
                            zoomOnMouseWheel: true,
                            showDetail: false,
                            left: '3%', // 滚动条靠左侧的百分比
                            bottom: 5,
                            start: 0, // 滚动条的起始位置
                            end: 30 // 滚动条的截止位置（按比例分割你的柱状图x轴长度）
                        }, {
                            type: 'inside',
                            xAxisIndex: [0],
                            start: 0,
                            end: 50
                        }
                    ],
                    grid: {
                        x: 50,
                        y: 55,
                        x2: 30,
                        y2: 55
                    }, // 设置图标旁边留白部分大小
                    xAxis: {
                        type: 'category',
                        data: this.lineXData,
                        axisLabel: { // X轴线 标签修改
                            formatter: function (val) {
                                return val.split(' ').join('\n')
                            },
                            textStyle: {
                                color: '#8c8c92' // 坐标值得具体的颜色
                            }
                        },
                        axisLine: {
                            show: true, // X轴 网格线 颜色类型的修改
                            lineStyle: {
                                type: 'solid',
                                color: '#eee'
                            }
                        }
                    },
                    yAxis: {
                        type: 'value',
                        splitLine: {
                            show: true,
                            lineStyle: {
                                type: 'dashed'
                            } // 设置刻度线条变成虚线
                        },
                        axisLabel: { // y轴线 标签修改
                            textStyle: {
                                color: '#8c8c92' // 坐标值得具体的颜色
                            }
                        },
                        axisLine: {
                            show: true, // y轴 网格线 颜色类型的修改
                            lineStyle: {
                                type: 'solid',
                                color: '#eee'
                            }
                        }
                    },
                    series: [{
                        name: '所有接口信息',
                        data: this.lineDataList,
                        type: 'line',
                        large: true,
                        smooth: true,
                        lineStyle: {
                            width: 1
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: '#d6e2ff'
                            }, {
                                offset: 1,
                                color: 'rgb(255, 255, 255)'
                            }])
                        }
                    }]
                })

                setTimeout(function () {
                    window.onresize = function () {
                        myPolylineChart.resize()
                        myChart.resize()
                    }
                }, 200)
            },

            // 获取选择服务数据
            getSelect() {
                this.$http.get('/EsbInboundMain/selectAllService').then(result => {
                    if (result.success) {
                        for (let i = 0; i < result.data.length; i++) {
                            this.infoForm.serviceOptions.push(result.data[i])
                        }
                    }
                })
            },
            // 获取服务名称
            getServname(servcode) {
                this.$http.get('/EsbInboundMain/selectServiceByServcode', {
                    servcode: servcode
                }).then(result => {
                    if (result.success) {
                        this.infoForm.servname = result.data[0].servname
                        this.infoForm.servversion = result.data[0].servversion
                        this.serviceid = result.data[0].serviceid
                    }
                })
            },

            visibleChange(val) {
                if (!val) {
                    this.$refs.select.blur()
                }
            },

            // 查询按钮
            queryChartData() {
                if (this.serviceid) {
                    this.flag = true
                    this.chartFlag = true
                    this.data = false
                    this.barYData = []
                    this.barDataList = []
                    this.lineXData = []
                    this.lineDataList = []
                    this.$http.get('/EsbLogSummary/selectServiceAnalysis', {
                        expid: this.serviceid,
                        requestEndTime: this.newTime[1],
                        requestStartTime: this.newTime[0]
                    }).then(result => {
                        if (result.success) {
                            this.height.height = '50%'
                            if (result.data.histogram.length === 0) {
                                this.chartFlag = false
                            }
                            this.curve = result.data.curve
                            // 柱状图数据处理
                            for (let i = 0; i < result.data.histogram.length; i++) {
                                this.barYData.push(result.data.histogram[i].histogramName)
                                this.barDataList.push(result.data.histogram[i].histogramCount)
                            }
                            // 折线图数据处理
                            for (let i = 0; i < result.data.curve.length; i++) {
                                this.lineXData.push(result.data.curve[i].date)
                                this.lineDataList.push(result.data.curve[i].num)
                                this.details.push(result.data.curve[i].detail)
                            }
                            this.getEchart()
                        }
                    })
                } else {
                    this.$message({
                        type: 'info',
                        message: '请选择服务名称！'
                    })
                }
            },

            // 下载
            download() {
                if (this.serviceid) {
                    let api = window.localStorage.getItem('ajaxApi') || '_/api',
                        obj = {
                            expid: this.serviceid,
                            requestEndTime: this.newTime[1],
                            requestStartTime: this.newTime[0]
                        }
                    window.open(location.origin + api + '/EsbLogSummary/serviceAnalysisDownload?' + qs.stringify(obj))
                    this.$message({
                        type: 'success',
                        message: '下载成功！'
                    })
                } else {
                    this.$message({
                        type: 'info',
                        message: '请选择服务名称！'
                    })
                }
            }
        },
        components: {
            breadcrumb
        }
    }
</script>

<style scoped lang="less">
    // 修改时间日期选择器的样式
    .el-date-editor {
        position: relative;
        padding-left: .25rem;

        & /deep/ .el-icon-time {
            position: absolute;
            top: 0;
            right: .1rem;

            &::before {
                content: '\E78E';
            }
        }

        & /deep/ .el-range-input {
            width: 42%;
        }

        & /deep/ .el-range__close-icon {
            display: none;
        }
    }

    .content {
        width: 100%;

        .img {
            text-align: center;

            img {
                width: 2.6rem;
                /*height: 1.2rem;*/
                margin-top: 10%;
            }

            div {
                color: #ccc;
                font-size: .14rem;
                /*margin-top: .2rem;*/
            }
        }

        .bar-chart {
            width: 100%;
            height: 100%;
            padding-bottom: .3rem;

            p {
                float: left;
                line-height: .4rem;
                font-size: .16rem;
            }

            .box {
                width: 90%;
                height: 3rem;
            }

            span i {
                font-size: .22rem;
                color: #999;
            }

            span i:hover {
                color: #5586FB;
            }
        }

        .polyline-chart {
            min-height: 4rem;
            height: 50%;

            .polyline-box {
                width: 90%;
                height: 3.5rem;
            }
        }
    }
</style>
